/******************************************************************************
 * Copyright (C) 2015  671643387@qq.com
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 *****************************************************************************/

#include "NodeCpp/Util/OptionSet.h"
#include "NodeCpp/Util/Option.h"

namespace NodeCpp {
namespace Util {

    OptionSet::OptionSet(void)
        : Options_()
    {

    }

    OptionSet::~OptionSet(void)
    {

    }

    void OptionSet::AddOption(const Option& _Option)
    {
        OptionArray::const_iterator _Iter = Options_.begin();
        for (; _Iter != Options_.end(); ++_Iter)
        {
            if (_Iter->name() == _Option.name())
                return;
        }
        Options_.push_back(_Option);
    }

    void OptionSet::Process(std::vector<std::string>& _Args)
    {
        std::vector<std::string>::iterator _ArgIter = _Args.begin();
        for (; _ArgIter != _Args.end();)
        {
            bool _UnknownArg = true;
            OptionArray::iterator _OptionIter = Options_.begin();
            for (; (_OptionIter != Options_.end() && _ArgIter != _Args.end()); ++_OptionIter)
            {
                if (_OptionIter->MatchName(*_ArgIter) || _OptionIter->MatchShortName(*_ArgIter))
                {
                    _ArgIter = _Args.erase(_ArgIter);
                    if (_OptionIter->HasArg() && _ArgIter != _Args.end())
                    {
                        _OptionIter->SetValue(*_ArgIter);
                        _OptionIter->SetValid(true);
                        _ArgIter = _Args.erase(_ArgIter);
                    }
                    else if (!_OptionIter->HasArg()) {
                        _OptionIter->SetValid(true);
                    }
                    _UnknownArg = false;

                    break;
                }
            }

            if (_UnknownArg) {
                ++_ArgIter;
            }
        }
    }

}}
